import hashlib
import re
import uuid
from datetime import datetime, timedelta

import bcrypt


def hash_password(password):
    """使用bcrypt哈希密码"""
    # 生成盐并哈希密码
    salt = bcrypt.gensalt()
    hashed_password = bcrypt.hashpw(password.encode('utf-8'), salt)
    return hashed_password.decode('utf-8')  # 转换为字符串存储

def verify_password(plain_password, hashed_password):
    """验证密码是否匹配"""
    try:
        # 将字符串转换回bytes进行比较
        return bcrypt.checkpw(
            plain_password.encode('utf-8'),
            hashed_password.encode('utf-8')
        )
    except Exception:
        return False


def is_valid_email(email):
    """验证邮箱格式"""
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return re.match(pattern, email) is not None


def is_valid_username(username):
    """验证用户名格式（支持中文，2-20个字符，不能为空）"""
    # 检查是否为空
    if not username or len(username.strip()) == 0:
        return False
    # 支持中文、字母、数字、下划线，长度2-20个字符
    pattern = r'^[\u4e00-\u9fa5a-zA-Z0-9_]{2,20}$'
    return re.match(pattern, username) is not None

def is_valid_password(password):
    """验证密码格式（6-20位字母+数字）"""
    if len(password) < 6 or len(password) > 20:
        return False
    if not any(char.isdigit() for char in password):
        return False
    if not any(char.isalpha() for char in password):
        return False
    return True

def generate_token():
    """生成token"""
    return str(uuid.uuid4())

def get_token_expires(remember_me=False):
    """获取token过期时间"""
    if remember_me:
        return datetime.now() + timedelta(days=7)  # 记住我时有效期7天
    else:
        return datetime.now() + timedelta(hours=2)  # 否则2小时